# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from functools import wraps

from flask import g, session, request, redirect, url_for, current_app, abort

def login_required(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        not_in_g = not hasattr(g, 'user') or g.user is None
        not_in_s = not 'user' in session or session['user'] is None
        if not_in_g and not_in_s:
            if 'confirm_route' in current_app.config:
                _route = current_app.config['confirm_route']
            else:
                _route = current_app.config['login_route']
            return redirect(url_for(_route, next=request.url))
        return func(*args, **kwargs)
    return decorated_function

def admin_required(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        in_g = hasattr(g, 'user') and not getattr(g, 'user') is None
        in_s = 'user' in session and not session['user'] is None
        if in_g or in_s:
            g_admin = in_g and getattr(g, 'user').is_admin
            s_admin = in_s and 'is_admin' in session['user'] and bool(session['user']['is_admin'])
            if g_admin or s_admin:
                return func(*args, **kwargs)
            else:
                return abort(403)
        else:
            if 'confirm_route' in current_app.config:
                _route = current_app.config['confirm_route']
            else:
                _route = current_app.config['login_route']
            return redirect(url_for(_route, next=request.url))
    return decorated_function

def public_network_protection(func):
    @wraps(func)
    def decorated_function(*args, **kwargs):
        public_can_acess = 'public_can_acess' in session and not session['public_can_acess'] is None
        if not public_can_acess:
            lan_ips = current_app.cache.get('lan_ips')
            if bool(lan_ips):
                _ip = request.remote_addr
                public_can_acess = _ip in lan_ips
        if not public_can_acess:
            return redirect(url_for('login'))
        else:
            return func(*args, **kwargs)
    return decorated_function